<template>
  <div>
    <div class="top">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>访客记录</span>
        </div>
        <el-input
          style="width: 250px; margin-right: 30px"
          placeholder="请输入姓名"
          v-model="pages.idorname"
        ></el-input>
        <el-input
          style="width: 250px; margin-right: 30px"
          placeholder="请输入手机号"
          v-model="pages.mobile"
        ></el-input>
        <el-input
          style="width: 250px; margin-right: 30px"
          placeholder="请输入身份证号"
          v-model="pages.card"
        ></el-input>
        <el-input
          style="width: 250px; margin-right: 30px"
          placeholder="请输入车牌号"
          v-model="pages.carnumber"
        ></el-input>
        <el-button type="primary" @click="getvisituser">查询</el-button>
      </el-card>
    </div>
    <div class="btn">
      <el-button type="primary" @click="dialogVisibles(true)">添加</el-button>
      <el-button type="danger" @click="delAll">批量删除</el-button>
      <el-button type="success" @click="D">导出</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="username" v-model="pages.username" label="姓名">
      </el-table-column>
      <el-table-column
        prop="mobile"
        v-model="pages.mobile"
        label="电话号码"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="card"
        v-model="pages.reason"
        label="身份证号"
      ></el-table-column>
      <el-table-column
        prop="carnumber"
        v-model="pages.carnumber"
        label="车牌号"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="reason"
        v-model="pages.reason"
        label="目的"
      ></el-table-column>
      <el-table-column label="操作" v-slot:default="scope">
        <el-button type="danger" @click="del(scope.row.v_id)" size="mini"
          >删除</el-button
        >
        <el-button
          type="primary"
          @click="dialogVisibles(false, scope.row, scope.row)"
          size="mini"
          >修改</el-button
        >
        <el-button type="success" @click="XQ(scope.row.v_id)" size="mini"
          >详情</el-button
        >
      </el-table-column>
    </el-table>

    <!-- 添加 修改弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div class="inp">
        <el-form
          ref="formInline"
          :model="formInline"
          label-width="80px"
          status-icon
          :rules="rules"
        >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="formInline.username" maxlength="4"></el-input>
          </el-form-item>

          <el-form-item label="电话号码" prop="mobile">
            <el-input v-model="formInline.mobile" maxlength="11"></el-input>
          </el-form-item>

          <el-form-item label="身份证号" prop="card">
            <el-input v-model="formInline.card" maxlength="18"></el-input>
          </el-form-item>

          <el-form-item label="车牌号" prop="carnumber">
            <el-input v-model="formInline.carnumber" maxlength="8"></el-input>
          </el-form-item>

          <el-form-item label="目的" prop="reason">
            <el-input v-model="formInline.reason"></el-input>
          </el-form-item>

          <div style="display: flex">
            <el-form-item label="进校时间" prop="starttime">
              <el-date-picker
                v-model="formInline.starttime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="离校时间"
              prop="endtime"
              style="margin-left: 20px"
            >
              <el-date-picker
                v-model="formInline.endtime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </div>
        </el-form>

        <el-radio-group v-model="type">
          <el-radio :label="1">临时访问登记</el-radio>
          <el-radio :label="2">在校生访问登记</el-radio>
        </el-radio-group>

        <div style="display: flex">
          <div style="display: flex; margin-top: 20px">
            <span style="margin-left: 10px">行程码</span
            ><el-upload
              class="avatar-uploader"
              action="http://121.42.230.80/api/visit/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              style="margin-left: 35px"
              prop="travelcode"
            >
              <img
                v-if="formInline.travelcode"
                :src="formInline.travelcode"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <div style="display: flex; margin-top: 20px; margin-left: 20px">
            <span>健康码</span
            ><el-upload
              class="avatar-uploader"
              action="http://121.42.230.80/api/visit/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccesss"
              :before-upload="beforeAvatarUploads"
              style="margin-left: 35px"
            >
              <img
                v-if="formInline.healthcode"
                :src="formInline.healthcode"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <div style="display: flex; margin-top: 20px; margin-left: 20px">
            <span>核酸</span
            ><el-upload
              class="avatar-uploader"
              action="http://121.42.230.80/api/visit/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccessss"
              :before-upload="beforeAvatarUploadss"
              style="margin-left: 35px"
            >
              <img
                v-if="formInline.nucleicacid"
                :src="formInline.nucleicacid"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormData(status)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <div class="botm">
      <el-pagination
        v-if="this.tableData.length > 0"
        style="margin-left: 35%; margin-top: 30px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pages.page"
        :pageSizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { log } from '../api/api';
import {
  visituser,
  visituserdel,
  visituseradd,
  visituseredit,
} from "../api/visitor";
import LogVue from './Log.vue';
export default {
  name: "VisitVisitor",

  data() {
    return {
      listexcels:'',
      // 校验
      rules: {
        username: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 4, message: "长度在1-4个字符", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "手机号码不符合规范", trigger: "blur" },
        ],
        card: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            min: 18,
            max: 18,
            message: "身份证号不正确,请检查",
            trigger: "blur",
          },
        ],
        carnumber: [
          { required: true, message: "请填写车牌号", trigger: "blur" },
          { min: 8, max: 8, message: "车牌号填写不正确", trigger: "blur" },
        ],
        reason: [
          { required: true, message: "请输入来学校的目的", trigger: "blur" },
          { min: 5, max: 20, message: "请输入来学校的目的", trigger: "blur" },
        ],
        starttime: [
          { required: true, message: "请输入进校时间", trigger: "blur" },
        ],
        endtime: [
          { required: true, message: "请输入离校时间", trigger: "blur" },
        ],
      },
      excel: {
        page:'',
        pageSize:'',
        idorname: "",
        mobile: "",
        card: "",
        carnumber: "",
        starttime: "",
        endtime: "",
        department: "",
        status: "",
      },
      imageUrl: "",
      serch: "",
      title: "",
      multipleSelection: [],
      tableData: [],
      ids: [],
      type: 1,
      show: false,
      pages: {
        page: 1,
        pageSize: 5,
        total: 0,
        username: "",
        mobile: "",
        card: "",
        carnumber: "",
        starttime: "",
        idorname: "",
      },
      dialogs: false,
      dialogVisible: false,
      status: "",
      formInline: {
        username: "",
        mobile: " ",
        card: " ",
        carnumber: " ",
        starttime: "",
        endtime: "",
        reason: " ",
        type: 1,
        department: 1, //部门
        travelcode: "", //行程码
        healthcode: "", //健康码
        nucleicacid: "", //核酸
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      value1: "",
      value2: "",
      value3: "",
    };
  },

  mounted() {
    this.getvisituser();
  },

  methods: {
    // 导出
    D() {
      console.log(this.excel);
      location.href = "http://121.42.230.80/api/visit/visituser/listexcel?listexcels="+this.excel;
    },
    // 详情
    XQ(data) {
      this.$router.push({
        name: "VisitorRecordDetails",
        params: {
          id: data,
        },
      });
    },
    // 判断修改 添加
    dialogVisibles(show, v_id, data) {
      this.status = show;
      this.v_id = v_id;
      if (show == true) {
        this.title = "添加";
        this.dialogVisible = true;
      } else {
        this.title = "修改";
        this.title = "详情";
        this.dialogVisible = true;
        // console.log(data)
        this.formInline = data;
      }
    },
    // 单删
    async del(v_id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          visituserdel({ v_id: v_id }).then((res) => {
            if (res.code == "00000") {
              this.getvisituser();
            }
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批删
    async delAll() {
      if (this.multipleSelection.length == 0) {
        return this.$message.error("请勾选");
      }
      let arr = [];
      this.multipleSelection.forEach((item) => {
        // console.log(item)
        arr.push(item.v_id);
      });

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          visituserdel({ v_id: arr }).then((res) => {
            if (res.code == "00000") {
              this.getvisituser();
            }
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      // console.log(arr);
    },
    // 添加  修改
    async addFormData(status) {
      if (status) {
        let res = await visituseradd({
          type: this.formInline.type,
          username: this.formInline.username,
          mobile: this.formInline.mobile,
          card: this.formInline.card,
          carnumber: this.formInline.carnumber,
          starttime: this.formInline.starttime,
          endtime: this.formInline.endtime,
          reason: this.formInline.reason,
          department: this.formInline.department, //部门
          travelcode: this.formInline.travelcode, //行程码
          healthcode: this.formInline.healthcode, //健康码
          nucleicacid: this.formInline.nucleicacid, //核酸
          adduserid: JSON.parse(sessionStorage.getItem("admin")).admin_id, // 添加人id 在sessionStorage中获取（登录时存的用户信息）
        });
        console.log(res);
        if (
          this.formInline.username == "" ||
          this.formInline.mobile == "" ||
          this.formInline.card == "" ||
          this.formInline.carnumber == "" ||
          this.formInline.starttime == "" ||
          this.formInline.endtime == "" ||
          this.formInline.reason == ""
        ) {
          this.dialogVisible = true;
          this.$message.error("表单数据不能为空");
        } else if (res.code == "00000") {
          this.getvisituser();
          this.dialogVisible = false;
          this.$refs.formInline.resetFields();
          this.$message.success("添加成功");
        }
      } else {
        let res = await visituseredit({
          id: this.v_id,
          formdata: {
            username: this.formInline.username,
            mobile: this.formInline.mobile,
            card: this.formInline.card,
            carnumber: this.formInline.carnumber,
            starttime: this.formInline.starttime,
            endtime: this.formInline.starttime,
            reason: this.formInline.reason,
            department: this.formInline.department,
            travelcode: this.formInline.travelcode,
            healthcode: this.formInline.healthcode,
            nucleicacid: this.formInline.nucleicacid,
          },
        });
        // console.log(res);
        if (res.code == "00000") {
          this.$message.success("修改成功");
          this.getvisituser();
          this.dialogVisible = false;
        }
      }
    },
    // 访客列表
    async getvisituser() {
      const res = await visituser({
        idorname: this.pages.idorname,
        mobile: this.pages.mobile,
        page: this.pages.page,
        pageSize: this.pages.pageSize,
        card: this.pages.card,
        carnumber: this.pages.carnumber,
      });
      if (res.code == "00000") {
        this.tableData = res.data;
        this.total = res.total;
      }
    },
    // 行程码
    handleAvatarSuccess(res, file) {
      this.formInline.travelcode = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 健康码
    handleAvatarSuccesss(res, file) {
      this.formInline.healthcode = URL.createObjectURL(file.raw);
    },
    beforeAvatarUploads(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 核酸
    handleAvatarSuccessss(res, file) {
      this.formInline.nucleicacid = URL.createObjectURL(file.raw);
    },
    beforeAvatarUploadss(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 分页条数，当前页
    handleSizeChange(val) {
      this.pages.pageSize = val;
      this.getvisituser();
    },
    handleCurrentChange(val) {
      this.pages.page = val;
      this.getvisituser();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style>
.el-table .cell,
.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ps {
  margin-top: 30px;
}
</style>

<style lang="less" scoped>
.botm {
  margin-top: 30px;
}
.el-table-column--selection el-table__cell {
  text-align: center;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.btn {
  margin: 20px 0px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>